<?php
/**
 * 云门店
 */
defined( 'IN_IA' )or exit( 'Access Denied' );

class j_hmoneyModuleReceiver extends WeModuleReceiver {

    public function receive() {
        global $_W;
        $openid = $this->message[ 'from' ];
        $card_id = $this->message[ 'cardid' ];
        $code = $this->message[ 'usercardcode' ];
        $event = $this->message[ 'event' ];

        $cfg = $this->module[ 'config' ];
        if ($cfg['debug'])$this->sendText($openid, "【调试信息】事件：".$event );
        if (!$cfg['wxmembercard']) return;
        if($card_id!=$cfg['wxmembercard'])return;
        if ( $event == 'user_get_card' ) {

        } elseif ( $event == 'submit_membercard_user_info' ) {

        } elseif ( $event == 'update_member_card' ) {

        } elseif ( $event == 'user_view_card' ) {
            load()->model( 'mc' );
            if ($cfg[ 'debug' ])$this->sendText( $openid,"1-接口正常-enter");
            $memberCard = pdo_fetch( "SELECT * FROM " . tablename( "j_hmoney_membercard" ) . " WHERE openid=:a order by id asc", array( ":a" => $openid ));
            if ($cfg[ 'debug' ])$this->sendText( $openid,"2-检查该会员卡是否存在");
            if(!$memberCard)return;
            if ($cfg[ 'debug' ])$this->sendText( $openid,"3-openid存在会员卡数据");
            $uid = $memberCard[ "uid" ];
            if (!$uid) {
                $uid = mc_openid2uid($openid);
                pdo_update("j_hmoney_membercard", array("uid" => $uid), array( "id" => $memberCard['id']));
            }
            $cash = $memberCard[ 'cash' ];
            $credit = $memberCard[ 'credit' ];
            if ( $cfg[ 'debug' ] )$this->sendText($openid, "4-读取通用会员数据");
            if ($uid) {
                if ($cfg[ 'debug' ])$this->sendText( $openid, "成功读取-search" );
                /*同步积分*/
                if ($credit * 100>0) {
                    $flag = mc_credit_update($uid, "credit1", $credit, array( "", "收银台消费积分转移" ) );
                    if ( $flag )pdo_update( "j_hmoney_membercard", array( "credit" => 0 ), array( "id" => $memberCard[ 'id' ] ) );
                }
                $creditAry = mc_credit_fetch($uid, array('credit1'));
                $credit = $creditAry[ 'credit1' ];
                /*同步余额*/
                if ( $cfg[ 'isgeneralbalance' ] ) {
                    if ( $cash > 0 ) {
                        $flag = mc_credit_update( $uid, "credit2", sprintf( '%.2f', ($cash * 0.01 ) ), array( "", "收银台消费余额转移" ) );
                        if ( $flag )pdo_update( "j_hmoney_membercard", array( "cash" => 0 ), array( "id" => $memberCard[ 'id' ] ) );
                    }
                    $creditAry2 = mc_credit_fetch( $uid, array( 'credit2' ) );
                    $cash = intval( $creditAry2[ 'credit2' ] * 100 );
                }
                /*同步会员等级*/
                $userinof=mc_fetch($uid);
                if ($memberCard[ 'gid' ] != $userinof[ 'groupid' ]) {
                    pdo_update( "j_hmoney_membercard", array( "gid" => $userinof['groupid' ] ), array( "id" => $memberCard[ 'id' ] ) );
                }
            }
            end:
            if ( $cfg[ 'debug' ] )$this->sendText($openid,"积分：".$credit."；余额：".$cash);
            load()->func( 'communication' );
            $acid = pdo_fetchcolumn( "SELECT acid FROM " . tablename( 'account' ) . " WHERE uniacid=:uniacid ", array( ':uniacid' => $_W[ 'uniacid' ] ) );
            $acc = WeAccount::create( $acid );
            $tokens = $acc->fetch_token();
            $data = array(
                "card_id" => $card_id,
                "code" => $code,
                "bonus" => intval( $credit ),
                "custom_field_value1" => strval(sprintf( '%.2f', ($cash * 0.01 ) )),
            );
            $pageparama = urldecode( json_encode( $data ) );
            $resp = ihttp_request( "https://api.weixin.qq.com/card/membercard/updateuser?access_token=" . $tokens, $pageparama, "" );
            $result = @json_decode( $resp[ 'content' ], true );
            if ( $cfg[ 'debug' ] )$this->sendText( $openid,"【最后】同步结果：".implode( ",", $result ) );
        }
        return;
    }


    private function sendText( $openid, $txt ) {
        global $_W;
        $acid = $_W[ 'account' ][ 'acid' ];
        if ( !$acid )$acid = pdo_fetchcolumn( "SELECT acid FROM " . tablename( 'account' ) . " WHERE uniacid=:uniacid ", array( ':uniacid' => $_W[ 'uniacid' ] ) );
        $acc = WeAccount::create( $acid );
        $data = $acc->sendCustomNotice( array( 'touser' => $openid, 'msgtype' => 'text', 'text' => array( 'content' => urlencode( $txt ) ) ) );
        return $data;
    }
}